package bizsocket.base;

import com.google.gson.Gson;

import bizsocket.tcp.Packet;
import okio.ByteString;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;

/**
 * JSONResponseConverter
 *
 * @since 2021-05-06
 */
public class JSONResponseConverter implements ResponseConverter {
    @Override
    public Object convert(int command, ByteString requestBody, Type type, Packet packet) {
        if (type == String.class) {
            return packet.getContent();
        } else if (type == JSONObject.class) {
            try {
                return new JSONObject(packet.getContent());
            } catch (JSONException e) {
                e.fillInStackTrace();
            }

        } else {
            return new Gson().fromJson(packet.getContent(), type);
        }
        return null;
    }
}
